package com.fzy.common.ftp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.function.Consumer;

import org.apache.commons.net.ftp.FTPClient;

/**
 * @describe 读取FTP上的文件
 * 
 */
public class FtpService {

	private FTPClient ftpClient;
	private String ip = null;
	private String username = null;
	private String password = null;
	private int port = -1;

	public FtpService(String ip, int port, String username, String password) {

		try {
			this.ftpClient = new FTPClient();
			this.ip = ip;
			this.port = port;
			this.username = username;
			this.password = password;
			this.connect();
			if (!this.ftpClient.isConnected()) {
				throw new RuntimeException();
			}
		} catch (Exception e) {

		}

	}

	private void connect() {
		try {
			this.ftpClient.connect(this.ip, this.port);
			this.ftpClient.login(this.username, this.password);
		} catch (Exception e) {

		}
	}

	public void shutdown() {
		try {
			if (this.ftpClient.isConnected()) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (IOException e) {

		}

	}
	public void readFile(String path, String filename, Consumer<? super InputStream> consumer) {

		try {
			//boolean f = ftpClient.sendCommand(new FTPCommand("grep -F -v -f a.file b.file > c.txt"));
			this.ftpClient.changeWorkingDirectory(path);
			InputStream stream = ftpClient.retrieveFileStream(filename);
			if (stream == null) {
				return;
			}
			consumer.accept(stream);

		} catch (Exception e) {

		}

	}

	public static void main(String[] args) throws ParseException, IOException {
		FtpService ftp = new FtpService("10.123.177.36", 21, "sms8822", "5dSAWClK");
		ftp.readFile("/mnt/data/ftpuser/sms8822", "M000000_20160216.txt", (in) -> {

			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
				String line = null;
				while ((line = reader.readLine()) != null) {
					System.out.println(line);
				}
				reader.close();
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {

			}

		});
	}
}
